/**
 * 文件上传组件
 */
import React, { useState } from 'react';
import { Upload, message, Button, Space, Card } from 'antd';
import { InboxOutlined, DeleteOutlined, FileTextOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';

const { Dragger } = Upload;

interface FileUploadProps {
  onFilesChange: (files: File[]) => void;
  disabled?: boolean;
}

const FileUpload: React.FC<FileUploadProps> = ({ onFilesChange, disabled = false }) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const props: UploadProps = {
    name: 'file',
    multiple: true,
    fileList,
    beforeUpload: (file) => {
      // 验证文件类型
      const isValidType = file.type === 'application/pdf' || 
                          file.type.startsWith('image/');
      if (!isValidType) {
        message.error(`${file.name} 不是有效的文件类型。请上传PDF或图片文件。`);
        return Upload.LIST_IGNORE;
      }

      // 验证文件大小（限制50MB）
      const isValidSize = file.size / 1024 / 1024 < 50;
      if (!isValidSize) {
        message.error(`${file.name} 文件大小超过50MB限制。`);
        return Upload.LIST_IGNORE;
      }

      return false; // 阻止自动上传
    },
    onChange: (info) => {
      // 处理文件列表变化
      const newFileList = info.fileList.map(file => ({
        ...file,
        status: 'done' as const,
      }));
      
      setFileList(newFileList);
      
      // 通知父组件文件列表变化
      const files = newFileList
        .filter(f => f.originFileObj)
        .map(f => f.originFileObj as File);
      onFilesChange(files);
    },
    onRemove: (file) => {
      const newFileList = fileList.filter(f => f.uid !== file.uid);
      setFileList(newFileList);
      
      // 通知父组件文件列表变化
      const files = newFileList
        .filter(f => f.originFileObj)
        .map(f => f.originFileObj as File);
      onFilesChange(files);
    },
    showUploadList: false, // 使用自定义列表展示
  };

  const handleClearAll = () => {
    setFileList([]);
    onFilesChange([]);
  };

  return (
    <div>
      <Dragger {...props} disabled={disabled} style={{ marginBottom: 16 }}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
        <p className="ant-upload-hint">
          支持单个或批量上传。支持PDF和图片格式，单个文件不超过50MB
        </p>
      </Dragger>

      {fileList.length > 0 && (
        <Card 
          title={`已选择 ${fileList.length} 个文件`} 
          extra={
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />}
              onClick={handleClearAll}
              disabled={disabled}
            >
              清空全部
            </Button>
          }
          size="small"
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            {fileList.map((file) => (
              <div 
                key={file.uid} 
                style={{ 
                  display: 'flex', 
                  justifyContent: 'space-between', 
                  alignItems: 'center',
                  padding: '8px 12px',
                  backgroundColor: '#f5f5f5',
                  borderRadius: '4px',
                }}
              >
                <Space>
                  <FileTextOutlined />
                  <span>{file.name}</span>
                  <span style={{ color: '#999', fontSize: '12px' }}>
                    ({((file.originFileObj?.size || 0) / 1024 / 1024).toFixed(2)} MB)
                  </span>
                </Space>
                <Button
                  type="text"
                  danger
                  size="small"
                  icon={<DeleteOutlined />}
                  onClick={() => props.onRemove?.(file)}
                  disabled={disabled}
                />
              </div>
            ))}
          </Space>
        </Card>
      )}
    </div>
  );
};

export default FileUpload;

